/*!

@author
*/
#include <stdafx.h>

#include "Camera.h"




void NavigationCamera::DirMove(float distance,int axis)
{
	Matrix rot;
	Vector3 rotDir = m_dir;
	switch(axis)
	{
	case 1:
		D3DXMatrixRotationY(&rot, PI/2.0f);
		rotDir.y=0;

		D3DXVec3TransformNormal(&rotDir, &rotDir, &rot);
		//rotDir= rot * rotDir;
		break;
	case 2:
		rotDir=Vector3(0,1,0);
		break;
	}

	m_pos = m_pos + (rotDir*distance);
}

void NavigationCamera::SetDirection(float yaw,float pitch,float roll)
{
	m_yaw = yaw;
	m_pitch = pitch;
	m_roll = roll;

	Matrix rx; D3DXMatrixRotationX(&rx, pitch);
	Matrix ry; D3DXMatrixRotationY(&ry, yaw);
	Matrix rz; D3DXMatrixRotationZ(&rz, roll);

	Matrix rot = (rx*(ry*rz));

	D3DXVec3TransformNormal(&m_dir, &Vector3(0,0,1), &rot);
}

void NavigationCamera::Update(float dt)
{
	//CoreEngine::IGraphicDevice*	pGraphicDevice	= CoreEngine::CoreEngineManager::GetInstance()->GetGraphicDevice();

	if(gInputManager->GetMouseButton(Mouse::BTN_RIGHT))
	{
		const float MOUSE_SPEED = 0.003f;

		static float dx=m_yaw,dy=m_pitch;
		static float cx=m_yaw,cy=m_pitch;
		dx+=(float)gInputManager->GetMouseDeltaX() * MOUSE_SPEED;
		dy+=(float)gInputManager->GetMouseDeltaY() * MOUSE_SPEED;

		const float toRad = PI / 180.0f;
		dy = Clamp<float>(dy,-89 * toRad,89 * toRad);
		m_pitch = dy;

		float step = dt * 12;
		if (step > 1.f)
			step = 1;

		cx += (dx-cx) * step;
		cy += (dy-cy) * step;

		SetDirection(cx,cy,0);
	}

	if (gInputManager->GetKey('W'))
		DirMove(dt*m_camSpeed,0);
	if (gInputManager->GetKey('S'))
		DirMove(dt*-m_camSpeed,0);
	if (gInputManager->GetKey('A'))
		DirMove(dt*-m_camSpeed,1);
	if (gInputManager->GetKey('D'))
		DirMove(dt*m_camSpeed,1);
	if (gInputManager->GetKey('Q'))
		DirMove(dt*m_camSpeed,2);
	if (gInputManager->GetKey('Z'))
		DirMove(dt*-m_camSpeed,2);


	const float minZ = .1f;
	const float maxZ = m_distance;

	Matrix matView, matProj;

	D3DXMatrixLookAtLH(&matView, &m_pos, &(m_pos + m_dir), &Vector3(0, 1, 0));
	D3DXMatrixPerspectiveFovLH(&matProj, 0.8f, 16.f/9.f, minZ, maxZ);

	Matrix matViewProj = matView * matProj;

	D3DXMatrixTranspose(&m_camInfo.view, &matView);
	D3DXMatrixTranspose(&m_camInfo.proj, &matProj);
	D3DXMatrixTranspose(&m_camInfo.view_proj, &matViewProj);

}
